$(function() {
	
	var flagIconClick = false;
	var TOP_WIDTH = 60;
	var TOP_EXPANDED_WIDTH = 240;
	var MORE_WIDTH = 300;
	var appRemoveAnimations = ['Poof','BounceOut','BackToMore','FlipOutX','FlipOutY','FadeOut'];
  window.timeLogsOn = false;

  window.AppSwitcher = {
    version_: '',
    appSwitcherSetting_: '',
    vascoApp : null,
    appswitcherSetting : 'default',
    displayTooltipLock : false,
    topMenuOpen_: true,
    topMenuAlwaysOpen_: true,
    topMenuExpanded_: false,
    topMenuAlwaysExpanded_: false,
    moreMenuOpen_: false,
    settingsOpen_: false,
		isDragging: false,
		placeHolderExpand: false,
		scroller: null
  }	
  
  AppSwitcher.init = function() {
		
    this.initAppSettings();
    this.overideSortableMethods();
    
    this.initToolTip();
    this.initElemBehaviors();
    this.initCloseBtn();
		this.initSetting();
		this.updateProductNames();
		this.runVascoApp();

		this.buildTopMenu();
		this.buildMoreMenu();

		this.initOverflow();
		
		this.highlightDoorway();
		this.initAnimation();
		// this.initTaskMonitoring();
		// 
		this.initTool();
		
		AppSwitcher.scroller = $('.antiscroll-box-wrap').antiscroll().data('antiscroll');
		$('.antiscroll-box, .antiscroll-box .antiscroll-inner').delay(1000).css('height',$(window)[0].innerHeight);
  }
  AppSwitcher.initTool = function() {
		$('.kd-segmentedcontrol').delegate('.kd-button', 'click', function(e){
			e.preventDefault();
			$(this).toggleClass('selected').siblings().removeClass('selected');

		});
	}
  AppSwitcher.initAppSettings = function() {
    var html = $('html');
    this.version_ = html.attr('version');
    this.appSwitcherSetting_ = html.attr('appswitcher-setting');
  };

	AppSwitcher.initSetting = function() {

    $('#appswitcher #setting').click(function() {
      AppSwitcher.settingsOpen_ = !AppSwitcher.settingsOpen_;
      AppSwitcher.moreMenuOpen_ = false;
      AppSwitcher.updateMenuVisibility();
			AppSwitcher.updateMenuSize();
      return false;
    });

    $('#setting-panel-close').click(function() {
      AppSwitcher.settingsOpen_ = false;
			AppSwitcher.topMenuOpen_ = AppSwitcher.topMenuAlwaysOpen_;
      AppSwitcher.topMenuExpanded_ = false;
      AppSwitcher.moreMenuOpen_ = false;
      AppSwitcher.settingsOpen_ = false;
      AppSwitcher.updateMenuVisibility();
			AppSwitcher.updateMenuSize();
      return false;
    });
    
    $('#setting-panel-small, #setting-panel-large, #setting-panel-hide').click(function() {
      var expanded = $('#setting-panel-large').prop('checked');
      var hiding = $('#setting-panel-hide').prop('checked');

			$('#as-logo').toggleClass('open2',expanded);

      AppSwitcher.topMenuAlwaysExpanded_ = expanded;
      AppSwitcher.topMenuExpanded_ = expanded;
      AppSwitcher.topMenuAlwaysOpen_ = !hiding;
      AppSwitcher.updateMenuSizeForSetting();
    });

  }

	AppSwitcher.highlightDoorway = function() {
		
		// TODO: display temp docked doorway
		
		$('#doorway-indicator').css('display','none');
		
		if($('html').attr('data-product')=='google') {
			$('#main li[data-product=serp]').find('a').addClass('selected');
			return false;
		}
		
		$('#main li').each(function(){
			console.log($('html').attr('data-product'));
			if( $(this).attr('data-product')==$('html').attr('data-product') && !$(this).hasClass('vascoSubmenuItemCollapsed') ) {
				$(this).find('a').addClass('selected');
				$('#doorway-indicator').css('top',$(this).offset().top+12+'px').css('display','block');
				return false;
			}
		});
	}

  AppSwitcher.initAnimation = function() {
    $('#as-logo').addClass('enter');
		$('#more').css('display','block');
		$('#tooltip').css('display','block');

		var ele = $('#show-more');
		
		// ele.delay(3000).animate({ marginTop: '46px' }, 700, function() {
		// 	$('#new-product').addClass('animated bounceInLeft').css('display','block');//.delay(1000).removeClass('bounceInLeft');
		// 	
		// 	$(this).css('margin-top','0');
		// 	$('#new-product .new-product-icon').delay(3000).addClass('animated bounceIn').css('display','block');
		// });
  }
  
  AppSwitcher.initToolTip = function() {
    // show tooltips when mouseover
  	$('#appswitcher #main li,#appswitcher #show-more,#appswitcher #setting').live("mouseover",function() {
  		if(!AppSwitcher.topMenuExpanded_ && !AppSwitcher.topMenuAlwaysExpanded_) {
  			var top = $(this).offset().top-4;
  			var productName = $(this).find('.product-name').text().replace(' ','&nbsp;');
  			$('#tooltip p').html(productName);
				if(productName=='Apps')
					top +=10;
  			$('#tooltip').css('top', top+'px').addClass('kd-bubble-visible');
  		} else {
			  $('#tooltip').removeClass('kd-bubble-visible');
  		}
  	});

  	$('#tooltip').live("mouseover",function() {
			$('#tooltip').addClass('kd-bubble-visible');
		});
		$('#tooltip').live("mouseout",function() {
			$('#tooltip').removeClass('kd-bubble-visible');
		});

  	$('#appswitcher #main li,#appswitcher #show-more,#appswitcher #setting').live("mouseout",function() {
			if( !AppSwitcher.displayTooltipLock && !AppSwitcher.topMenuAlwaysExpanded_) {
			  $('#tooltip').removeClass('kd-bubble-visible');
			}
  	});
  }
  
  AppSwitcher.initElemBehaviors = function() {
		$('#expand-menu, #menu-title, #search-logo, #top-as-icon-box').click(function() {
			if (AppSwitcher.appSwitcherSetting_ == 'hide') {
				var open = AppSwitcher.topMenuOpen_;
				AppSwitcher.topMenuOpen_ = !open;
				AppSwitcher.topMenuExpanded_ = true;
				AppSwitcher.moreMenuOpen_ = false;
				AppSwitcher.settingsOpen_ = false;
				AppSwitcher.updateMenuVisibility();
				AppSwitcher.updateMenuSize();
				return;
			}
			AppSwitcher.topMenuOpen_ = true;
			AppSwitcher.topMenuExpanded_ = AppSwitcher.topMenuAlwaysExpanded_;
			AppSwitcher.moreMenuOpen_ = false;
			AppSwitcher.settingsOpen_ = false;
			AppSwitcher.updateMenuVisibility();
			AppSwitcher.updateMenuSize();
	    return false;
	  });
		
    $('#show-more,#more-shortcut,#hide-more').click(function() {
      AppSwitcher.moreMenuOpen_ = !AppSwitcher.moreMenuOpen_;
      AppSwitcher.settingsOpen_ = false;
      AppSwitcher.updateMenuVisibility();
			AppSwitcher.updateMenuSize();
      
      return false;
    });

  	$('#appswitcher #as-icon-box').click(function() {
      if (AppSwitcher.topMenuAlwaysOpen_) {
        AppSwitcher.topMenuExpanded_ = !AppSwitcher.topMenuExpanded_;
      } else {
				
				if(!AppSwitcher.topMenuAlwaysOpen_&&!AppSwitcher.topMenuAlwaysExpanded_){
					AppSwitcher.topMenuExpanded_ = !AppSwitcher.topMenuExpanded_;
				}
				else {
	        AppSwitcher.topMenuOpen_ = !AppSwitcher.topMenuOpen_;
	        AppSwitcher.moreMenuOpen_ = false;
	        AppSwitcher.settingsOpen_ = false;
				}
      }
			
      AppSwitcher.updateMenuVisibility();
			AppSwitcher.updateMenuSize();      
  		flagIconClick = true;
  	});

    $('html').click(function(e) {
      if ($(e.target).closest('.menu').length == 0 || $(e.target).attr('id')=='sortable-dropbox' ) {
        AppSwitcher.topMenuOpen_ = AppSwitcher.topMenuAlwaysOpen_;
        AppSwitcher.topMenuExpanded_ = false;
        AppSwitcher.moreMenuOpen_ = false;
        AppSwitcher.settingsOpen_ = false;
        AppSwitcher.updateMenuVisibility();
				AppSwitcher.updateMenuSize();
  		}
    });
  }

  AppSwitcher.buildMenuItems = function(builder, products, extraClasses) {
    extraClasses = extraClasses || '';
    
    for (var i = 0, n = products.length; i < n; i++) {
      var product = products[i];
      var customStyle = '';

      switch(product.id){

			case "messages":
        customStyle = [ 'background: url('+EXT_IMG_PATH+'ribbon/vasco-icons/messages.png) no-repeat;' ];
        break;
      case "maps":
        customStyle = [ 'background: url('+EXT_IMG_PATH+'ribbon/vasco-icons/maps.png) no-repeat;' ];
        break;
			case "play":
        customStyle = [ 'background: url('+EXT_IMG_PATH+'ribbon/vasco-icons/play.png) no-repeat;' ];
        break;
			case "shop":
        customStyle = [ 'background: url('+EXT_IMG_PATH+'ribbon/vasco-icons/shop.png) no-repeat;' ];
        break;
			case "hangout":
        customStyle = [ 'background: url('+EXT_IMG_PATH+'ribbon/vasco-icons/hangout.png) no-repeat;' ];
        break;
			case "drive":
        customStyle = [ 'background: url('+EXT_IMG_PATH+'ribbon/icons/drive_32.png) no-repeat;' ];
        break;
			case "hangout":
        customStyle = [ 'background: url('+EXT_IMG_PATH+'as-icons/vasco-hangout.png) no-repeat;left:18px;' ];
        break;
			case "youtube":
        customStyle = [ 'background: url('+EXT_IMG_PATH+'ribbon/vasco-icons/youtube.png) no-repeat;' ];
        break;
			case "news":
        customStyle = [ 'background: url('+EXT_IMG_PATH+'ribbon/vasco-icons/news.png) no-repeat;' ];
        break;
			case "larry":
        customStyle = [ 'background: url('+EXT_IMG_PATH+'ribbon/vasco-icons/phone.png) no-repeat;' ];
        break;
      default:
        customStyle = [ 'background: url('+EXT_IMG_PATH+'products-32.png); background-position: ', product.getOffsetX(32), 'px ',  product.getOffsetY(32), 'px;' ];
        break;
      }
      
      builder.push(
        '<li class="product-', product.id, ' ', extraClasses, '" data-product="', product.id, '">',
        '<a href="#', product.id, '">',
        '<span class="icon" style="');
      builder.push.apply(builder, customStyle);
      builder.push(
        '">',
        '</span>',
        '<span class="product-name">', product.name, '</span>',
        '</a>',
        '</li>'
      );
    }
  };
	
	AppSwitcher.animatePoof = function() {

			var bgTop = 0; // initial background-position for the poof sprit is '0 0'
			var frames = 5; // number of frames in the sprite animation
			var frameSize = 32; // size of poof <div> in pixels (32 x 32 px in this example)
			var frameRate = 40; // set length of time each frame in the animation will display (in milliseconds)

			// loop through amination frames
			// and display each frame by resetting the background-position of the poof <div>
			for(i=1;i<frames;i++) {
				$('.poof').animate({
					backgroundPosition: '0 ' + (bgTop - frameSize) + 'px'
				}, frameRate);
				bgTop -= frameSize; // update bgPosition to reflect the new background-position of our poof <div>
			}
			// wait until the animation completes and then hide the poof <div>
			setTimeout("$('.poof').hide()", frames * frameRate);
	}
	
  AppSwitcher.buildTopMenu = function() {
    var builder;
    var app = this.vascoApp;
    
    builder = [ ];
    this.buildMenuItems(builder, [ app.getActiveProduct() ]);
    $('#active').html(builder.join(''));

    builder = [ ];
    this.buildMenuItems(builder, uxe.Product.TOP);
    // var more = $('#show-more').detach();
		var newProduct = $('#new-product').detach();
    $('#appswitcher #main').html(builder.join('')).append(newProduct);
    
    var prod = app.getActiveProduct().dealias().id;
    $('#appswitcher #main .' + prod).addClass('highlight');
  }
  
  AppSwitcher.buildMoreMenu = function() {
    var builder;
    var app = this.vascoApp;
    var mru = app.getMRUProducts();
    
    builder = [ ];
    this.buildMenuItems(builder,uxe.Product.RECENT,["Doorway"]);
    $('#appswitcher #recent ol').html(builder.join(''));
    
    builder = [ ];
    this.buildMenuItems(builder, uxe.Product.MUCH_MORE,["Doorway"]);
    $('#appswitcher #remaining ol').html(builder.join(''));

    $( "#appswitcher #main,#appswitcher #morelist,#appswitcher #sortable-dropbox" ).sortable({
      connectWith: ".connectedSortable",
      revert: 120,
			appendTo: 'body',
			placeholder: 'ui-state-highlight',
			distance: 10,
			helper: 'clone',
			delay: 20,
			tolerance: 'pointer',
			scroll: false,
			forcePlaceholderSize: true
    });

		
		AppSwitcher.draggingFromMain_ = false;
		AppSwitcher.draggedOut_ = false;
		
		$( "#sortable-dropbox" ).bind( "sortreceive", function(event, ui) {
			$(this).empty();
		});
		
		
		$( "#appswitcher #main" ).bind( "sortstart", function(event, ui) {
			// $(ui.placeholder).slideUp();
  		AppSwitcher.draggingFromMain_ = true;
		});
	
		$( "#appswitcher #main li,#appswitcher #morelist" ).bind( "sortout", function(event, ui) {
			console.log('flash');
			$('#show-more').addClass('flash');
			AppSwitcher.draggedOut_ = true;
		});
		
		$( "#appswitcher #main" ).bind( "sortover", function(event, ui) {
			if (AppSwitcher.topMenuOpen_ && !AppSwitcher.topMenuExpanded_ && !AppSwitcher.moreMenuOpen_) {}
			else {
		    // make it same
				ui.helper.find('a').removeClass('more-vascoSubmenuItemDrag');
				ui.helper.find('a').addClass('main-vascoSubmenuItemDrag').addClass('enter');
				if ($('#appswitcher').hasClass('open2'))
				ui.helper.find('a').removeClass('open').addClass('open2');
				else {
				  ui.helper.find('.product-name').css('display', 'none');
				  ui.helper.find('a').removeClass('open2').addClass('open');
				}
			}
			$('#show-more').removeClass('flash');
			AppSwitcher.draggedOut_ = false;
		});
		
		$( "#morelist" ).bind( "sortover", function(event, ui) {
			if (AppSwitcher.topMenuOpen_ && !AppSwitcher.topMenuExpanded_ && !AppSwitcher.moreMenuOpen_) {}
			else if ($('#appswitcher').hasClass('more-open')) {
		    ui.helper.find('a').removeClass('main-vascoSubmenuItemDrag');
		    ui.helper.find('a').addClass('more-vascoSubmenuItemDrag').addClass('enter');

		    if ($('#appswitcher').hasClass('open2'))
		    ui.helper.find('a').removeClass('open').addClass('open2');
		    else {
		    	ui.helper.find('a').removeClass('open2').addClass('open');
		    }
		    ui.helper.find('.product-name').css('display', 'block');
			}
			$('#show-more').removeClass('flash');
			AppSwitcher.draggedOut_ = false;
		});

		$( "#appswitcher #main,#appswitcher #morelist" ).bind( "sortstart", function(event, ui) {
				
			var parentID = ui.item.closest("ol").attr("id"); // #main or #morelist
			ui.helper.find('a').removeClass('more-vascoSubmenuItemDrag')
			                   .removeClass('main-vascoSubmenuItemDrag')
			                   .removeClass('enter')
			                   .removeClass('open2')
			                   .removeClass('open');
			
			ui.helper.addClass('vascoSubmenuItemDrag')
			         .addClass('vascoSubmenuItem');
			
			ui.helper.find('a').addClass('vascoSubmenuItemLink');
			
			if( parentID=='main' ) {
 				ui.helper.find('a').addClass('main-vascoSubmenuItemDrag');

				if ($('#appswitcher').hasClass('open2'))
					ui.helper.find('a').addClass('open2');
				else {
					ui.helper.find('.product-name').css('display','none');
					ui.helper.find('a').addClass('open');
				}
			}
			else if( $('#appswitcher').hasClass('more-open') ) {
 				ui.helper.find('a').addClass('more-vascoSubmenuItemDrag');

				if ( $('#appswitcher').hasClass('open2') )
					ui.helper.find('a').addClass('open2');
				else
					ui.helper.find('a').addClass('open');

				ui.helper.find('.product-name').css('display','block');
			}
		});
	
		$( "#appswitcher #main,#appswitcher #morelist" ).bind( "sortchange", function(event, ui) {

			if( AppSwitcher.placeHolderExpand && ui.placeholder.isAnimating==false||ui.placeholder.isAnimating==null) {
				ui.placeholder.isAnimating = true;
				$(ui.placeholder).css('height','0px');
				$(ui.placeholder).animate({'height': '44px'}, 200, function(){ ui.placeholder.isAnimating=false; });
			}
			if( !AppSwitcher.placeHolderExpand )
				$(ui.placeholder).css('height','44px');
			
			if( !AppSwitcher.topMenuExpanded_ && $('#appswitcher').hasClass('more-open') && event.pageX<60 ) {				
				var moveX = event.pageX - ui.helper.offset().left-24;
			  ui.helper.css('padding-left',moveX+'px');
			}

		});

		$( "#appswitcher #main,#appswitcher #morelist" ).bind( "sortbeforestop", function(event, ui) {
			if (AppSwitcher.draggingFromMain_ && AppSwitcher.draggedOut_) {
			  ui.item.remove();
			}
			
			AppSwitcher.draggingFromMain_ = false;
		  AppSwitcher.draggedOut_ = false;
	  });
		
		$( "#appswitcher #main,#appswitcher #morelist" ).bind( "sortstop", function(event, ui) {
			// console.log('sortstop');
			$('#show-more').removeClass('flash');
			
			if( AppSwitcher.moreMenuOpen_ ) {
				$('#more').find('.product-name').css('display','block');
			}
			
			if(!AppSwitcher.topMenuExpanded_ && !AppSwitcher.topMenuAlwaysExpanded_) {
				$('#main .product-name, #show-more .product-name').css('display','none');
			}
			
			AppSwitcher.updateMenuVisibility();
			AppSwitcher.updateMenuSize();
			
			AppSwitcher.updateOverflow();
			AppSwitcher.highlightDoorway();
		});

  }
  
  AppSwitcher.initCloseBtn = function() {
	
    var closeMore = $('<a id="close-more" class="kd-closebutton" style="top: 8px;left: 246px;"></a>');
  	$('#appswitcher #remaining').after(closeMore);

  	closeMore.click(function(e) {
  	  AppSwitcher.moreMenuOpen_ = false;
  	  AppSwitcher.updateMenuVisibility();
			AppSwitcher.updateMenuSize();
    });
  }
  
  AppSwitcher.updateMenuVisibility = function() {
    var topAlwaysOpen = AppSwitcher.topMenuAlwaysOpen_;
    var topOpen = topAlwaysOpen || AppSwitcher.topMenuOpen_;
    var moreOpen = topOpen && AppSwitcher.moreMenuOpen_;
    var settingsOpen = topOpen && AppSwitcher.settingsOpen_;

		$('#top-as-icon-box').toggleClass('show',!topAlwaysOpen&&!topOpen);

    $('#appswitcher')
      .addClass('can-transition')
      .toggleClass('open', topOpen)
      .toggleClass('more-open', moreOpen);
    $('#setting-panel')
      .toggleClass('open', settingsOpen);
    $('#setting')
      .toggleClass('setting-open', settingsOpen);
    
    if (moreOpen) {
      $('#more')
        .scrollTop(0)
        .find('.product-name').css('display','block');
    }

    
    $('#customize-overlay')
      .addClass('customize-overlay-transition')
      .toggleClass('customize-overlay-visible', moreOpen || settingsOpen);
    
    if (moreOpen || settingsOpen) {
      $('#tooltip').removeClass('kd-bubble-visible');
    }
    AppSwitcher.updateMenuControls();

		if( !topAlwaysOpen && !topOpen )
			$('#sortable-dropbox').css('display','none');
		else
			$('#sortable-dropbox').css('display','block');
  };
  
	AppSwitcher.updateMenuSizeForSetting = function() {
    var alwaysOpen = AppSwitcher.topMenuAlwaysOpen_;
    var open = alwaysOpen || AppSwitcher.topMenuOpen_;
    var alwaysExpanded = AppSwitcher.topMenuAlwaysExpanded_;
    var expanded = alwaysExpanded || AppSwitcher.topMenuExpanded_;
    
    $('#main .product-name, #show-more .product-name, #bottom-menubar .product-name, #show-more .product-name').css('display', expanded ? 'block' : 'none');
    $('#setting .product-name').css('display', expanded ? 'block' : 'none');
    $('#logo').css('display', expanded ? 'block' : 'none');
    $('#appswitcher').toggleClass('open2', open && expanded);
		
    $('#setting-panel-preview').toggleClass('setting-panel-preview-large', alwaysExpanded);
    $('#app-bg, #search-logo, #search-box, #as-logo, #logo')
      .toggleClass('page-narrower', alwaysOpen && !alwaysExpanded)
      .toggleClass('page-narrowest', alwaysOpen && alwaysExpanded);
    
    AppSwitcher.updateMenuControls();
		// udpate sortable-dropbox width
		var pLeft = 0;
		if(AppSwitcher.topMenuOpen_)
			pLeft = TOP_WIDTH;
		if(AppSwitcher.topMenuExpanded_)
			pLeft = TOP_EXPANDED_WIDTH;
		if(AppSwitcher.moreMenuOpen_)
			pLeft += MORE_WIDTH;

		$('#sortable-dropbox').css('margin-left',pLeft+'px');
  };

  AppSwitcher.updateMenuSize = function() {
    var alwaysOpen = AppSwitcher.topMenuAlwaysOpen_;
    var open = alwaysOpen || AppSwitcher.topMenuOpen_;
    var alwaysExpanded = AppSwitcher.topMenuAlwaysExpanded_;
    var expanded = alwaysExpanded || AppSwitcher.topMenuExpanded_;
    
    $('#main .product-name, #show-more .product-name, #bottom-menubar .product-name, #show-more .product-name').css('display', expanded ? 'block' : 'none');
    $('#setting .product-name').css('display', expanded ? 'block' : 'none');
    $('#logo').css('display', expanded ? 'block' : 'none');
    $('#appswitcher').toggleClass('open2', open && expanded);

		$('#as-logo').toggleClass('open2', open && expanded);
		
    $('#setting-panel-preview').toggleClass('setting-panel-preview-large', alwaysExpanded);
    $('#app-bg, #search-logo, #search-box, #as-logo, #logo')
      .toggleClass('page-narrower', alwaysOpen && !alwaysExpanded)
      .toggleClass('page-narrowest', alwaysOpen && alwaysExpanded);
    
    AppSwitcher.updateMenuControls();

		
		// udpate sortable-dropbox width
		var pLeft = 0;
		if(AppSwitcher.topMenuOpen_)
			pLeft = TOP_WIDTH;
		if(AppSwitcher.topMenuExpanded_)
			pLeft = TOP_EXPANDED_WIDTH;
		if(AppSwitcher.moreMenuOpen_)
			pLeft += MORE_WIDTH;

		$('#sortable-dropbox').css('margin-left',pLeft+'px');
  };
  
  AppSwitcher.updateMenuControls = function() {
    var topAlwaysOpen = AppSwitcher.topMenuAlwaysOpen_;
    var topAlwaysExpanded = AppSwitcher.topMenuAlwaysExpanded_;
    var topExpanded = topAlwaysExpanded || AppSwitcher.topMenuExpanded_;
    
		// if( topAlwaysOpen || topAlwaysExpanded )
		//     	$('#as-logo').toggleClass('open2', !topAlwaysOpen || topExpanded);
  };
  
  
  AppSwitcher.runVascoApp = function() {
    var app = this.vascoApp = new uxe.VascoApp();
    app.onProductChange = function(product) {
      var productId = product.dealias().id;
			
      // gprotolog.log('App changed', product.name);
      
      AppSwitcher.topMenuExpanded_ = false;
      AppSwitcher.moreMenuOpen_ = false;
      AppSwitcher.settingsOpen_ = false;
      AppSwitcher.updateMenuVisibility();
			AppSwitcher.updateMenuSize();
      
			var selectedItem = $('#show-more, #main').find('.product-'+productId).find('a');
			
      $('#show-more, #main').find('.selected').removeClass('selected');
      selectedItem.addClass('selected');
			
			if(selectedItem.length>0) {
				$('#doorway-indicator').css('top',selectedItem.offset().top+14+'px').css('display','block');
			}
  		flagIconClick = false;

    };

    app.run();
  }
  
  AppSwitcher.updateProductNames = function() {
    if (AppSwitcher.version_ != 'wireframe') {
      return;
    }
    
    var makeProductClones = function(original, count, idPrefix, namePrefix) {
      var newProducts = [ ];
      for (var i = 0; i < count; i++) {
				if(idPrefix=='extra')
					newProducts[i] = original.clone(idPrefix + (i+1), namePrefix);
				else if(idPrefix=='default') {
					if(i>=7)
						newProducts[i] = original.clone('Custom' + (i-6), 'Custom ' + (i-6));
					else
        		newProducts[i] = original.clone(idPrefix + (i+1), namePrefix + (i+1));
				}
				else {
					newProducts[i] = original.clone(idPrefix + (i+1), namePrefix + (i+1));
				}
      }
      return newProducts;
    };

    var uxep = uxe.Product; // shorthand
    var original = uxep.forID('evenmore');
    
    uxep.SEARCH = original.clone('home', 'Home');
    uxep.DEFAULT = uxep.SEARCH;
    uxep.NEW_PRODUCT = original.clone('newproduct', 'Promo 1');
    
    uxep.TOP = makeProductClones(original, 9, 'default', 'Doorway ');
    
		uxep.MUCH_MORE = makeProductClones(original, uxep.MUCH_MORE.length, 'extra', 'Doorway');
    
    uxep.RECENT = uxep.MUCH_MORE.slice(0, 6);
  };
  
  AppSwitcher.initTaskMonitoring = function() {
    var taskMon = new uxe.TaskMonitor('8cf4c9c2-1d2c-4d56-9243-4b0af858a0c3');
    taskMon.start();
  };
  
  AppSwitcher.initOverflow = function() {
    $(window).resize(function() {
		
      AppSwitcher.updateOverflow();
			$('.antiscroll-box, .antiscroll-box .antiscroll-inner').css('height',this.innerHeight);
			AppSwitcher.scroller.refresh();
    });
    AppSwitcher.updateOverflow();
		$('.antiscroll-box, .antiscroll-box .antiscroll-inner').css('height',this.innerHeight);

  };
  
  AppSwitcher.lastItemCount_ = -1;
  AppSwitcher.lastVisibleItemCount_ = -1;
  
	AppSwitcher.overideSortableMethods = function() {
		$.ui.sortable.prototype._rearrange = function(event, i, a, hardRefresh) {
			
			if(this.direction=='up')
				AppSwitcher.placeHolderExpand = false;
			else
				AppSwitcher.placeHolderExpand = true;
			
			if(i!=null) {
				if(this.direction=='up' && i.item[0]!=null && (!i.item[0].isMoving||i.item[0].isMoving==null) ) {
					AppSwitcher.placeHolderExpand = false;
					i.item[0].isMoving = true;
					i.item.css('margin-top','44px');
					i.item.animate({'margin-top':'0px'}, {duration:200, complete:function() {
						this.isMoving = false;
					}});
				}		
				else if(this.direction=='down' && i.item[0]!=null && (!i.item[0].isMoving||i.item[0].isMoving==null) ) {
					AppSwitcher.placeHolderExpand = true;
				}
			}
						
			a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling));
			//Various things done here to improve the performance:
			// 1. we create a setTimeout, that calls refreshPositions
			// 2. on the instance, we have a counter variable, that get's higher after every append
			// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
			// 4. this lets only the last addition to the timeout stack through
			this.counter = this.counter ? ++this.counter : 1;
			var self = this, counter = this.counter;

			window.setTimeout(function() {
				if(counter == self.counter) self.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
			},0);

		}
		
		$.ui.sortable.prototype._mouseStop = function(event, noPropagation) {

			if(!event) return;

			//If we are using droppables, inform the manager about the drop
			if ($.ui.ddmanager && !this.options.dropBehaviour)
				$.ui.ddmanager.drop(this, event);

			if(this.options.revert) {

				var self = this;
				var cur = self.placeholder.offset();
				self.reverting = true;
				
				if($('#sortable-dropbox').offset().left>cur.left) {
					$(this.helper).animate({
						left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
						top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
					}, parseInt(this.options.revert, 10) || 500, function() {
						self._clear(event);
					});
				}
				else {
					var animationType = 'BackToMore';//$('.kd-segmentedcontrol .selected').text().replace(/^\s+|\s+$/g, '');
					var idx = jQuery.inArray(animationType, appRemoveAnimations);
					switch(idx) {
						case 0:
							var xOffset = 12;
							var yOffset = 20;
							$('.poof').css({
								left: event.pageX - xOffset + 'px',
								top: event.pageY - yOffset + 'px'
							}).show(); // display the poof <div>
							AppSwitcher.animatePoof(); // run the sprite animation
							this._clear(event, noPropagation);
							break;
						case 1:
							$(this.helper).addClass('animated bounceOut');
							var self = this;
							$(this.helper).delay(2000, "myQueue").queue("myQueue", function(){ 
							  self._clear(event, noPropagation); 
							}).dequeue("myQueue");
							break;
						case 2: //BackToMore
							var self = this;
							$(this.helper).animate({
								opacity: 0,
								left: $('#show-more').offset().left,//cur.left,
								top: $('#show-more').offset().top
							}, 250, function() {
								self._clear(event);
							});
							break;
						case 3:
							$(this.helper).addClass('animated flipOutX');
							var self = this;
							$(this.helper).delay(2000, "myQueue").queue("myQueue", function(){ 
							  self._clear(event, noPropagation); 
							}).dequeue("myQueue");
							break;
						case 4:
							$(this.helper).addClass('animated flipOutY');
							var self = this;
							$(this.helper).delay(2000, "myQueue").queue("myQueue", function(){ 
							  self._clear(event, noPropagation); 
							}).dequeue("myQueue");
							break;
						case 5:
							console.log('5');
							$(this.helper).addClass('animated fadeOutBlow');
							var self = this;
							$(this.helper).delay(2000, "myQueue").queue("myQueue", function(){ 
							  self._clear(event, noPropagation); 
							}).dequeue("myQueue");
							break;
					}
				}
			} else {
				this._clear(event, noPropagation);
			}

			return false;
		}
	}

  AppSwitcher.updateOverflow = function() {
    var OCCUPIED_SPACE = 250;//424; // TODO: Calculate on the fly
    var occupiedSpace = OCCUPIED_SPACE + (AppSwitcher.version_ == 'wireframe' ? 44 : 0);
    
    var height = $('#appswitcher #top').height();
    var heightLeft = height - occupiedSpace;
    var visibleItemCount = Math.max(0, Math.floor(heightLeft / 44));
    
    var items = $('#appswitcher #main li').get();
    var itemCount = items.length;
    
    if (itemCount == AppSwitcher.lastItemCount_ && 
        visibleItemCount == AppSwitcher.lastVisibleItemCount_) {
      return;
    }
    AppSwitcher.lastItemCount_ = itemCount;
    AppSwitcher.lastVisibleItemCount_ = visibleItemCount;
    
    var showItems = items.slice(0, visibleItemCount);
    var hideItems = items.slice(visibleItemCount);
    
		var selectedItem = $('#appswitcher #main').find('.selected');
		var selectedItemIdx = selectedItem.parent().index();

		if(selectedItemIdx!=-1) {
			if( selectedItemIdx>(visibleItemCount-1) )
				$('#appswitcher #doorway-indicator').css('display','none');
			else
				$('#appswitcher #doorway-indicator').css('display','block');
		}
		
    $(showItems).removeClass('vascoSubmenuItemCollapsed');
    $(hideItems).addClass('vascoSubmenuItemCollapsed');
    
    // TODO: Need a better way to get the products in the main menu
    var overflowProducts = hideItems.map(function(elem) {
      var productId = $(elem).attr('data-product');
      return uxe.Product.forID(productId);
    });
    
    var builder = [ ];
    AppSwitcher.buildMenuItems(builder, overflowProducts);
    $('#appswitcher #overflow')
      .toggle(overflowProducts.length > 0)
      .html( builder.join('') )
      .find('.product-name').css('display', 'block');

		if(overflowProducts.length>0)
			$('#appswitcher #flow').css('display','block');
		else
			$('#appswitcher #flow').css('display','none');
  };
	
	// AppSwitcher.init();
});